<?php

namespace Home\Controller;
use core\lib\Exception;
use Home\Org\Util\Sqlserver;
use Org\Util\UploadFile;
/**
 * 售前 售后服务
 * @author dem
 *
 */
class OrderController extends HomeController {
    
    function index(){
        $this->display('report/index');
    }
   
   
    
    /**
     * 分期-物料
     */
    function fqbywl(){
       
        $this->assign('src', 'rp2/plist2.php');
        $this->display('report/index');
    }
    
    /**
     * 分期-订单
     */
    function fqbyorder(){
        $this->assign('src', 'rp2/plist.php');
        $this->display('report/index');
    }
    
    /**
     * 积分 -订单
     */
    function jfbyorder(){
        $this->assign('src', 'rp2/plist.php');
        $this->display('report/index');
    }
    
    /**
     * 积分 -物料
     */
    function jfbywl(){
        $this->assign('src', 'rp2/plist.php');
        $this->display('report/index');
    }
    
    function send(){
        $this->assign('src', '/sap/orderByItemCode.php');
        $this->display('report/index');
    }
    
    
    function orderByItemCode(){
        $this->initialize();
        $date = date('Y-m-d',time());
        //and t.U_OStatus IN ('1', '3')  T.U_PManager='{$pm}' and
         $pm = session('Pleader');
        $sql = "SELECT top 1000 * FROM ( SELECT TOP 10  t.U_ItemCode ,t.U_ItemName,COUNT (1) AS ct FROM [@ti_z0081] AS t INNER JOIN [@ti_z0080] as t2 on t.DocEntry=t2.DocEntry WHERE t.U_Replace = 'Y' and t.U_OStatus IN ('1','2', '3') and t2.U_DocDate ='{$date}'  GROUP BY t.U_ItemCode,t.U_ItemName ) AS data ORDER BY ct DESC";
        //error_log($sql);
        $db = new Sqlserver();
        $db->connent();
        $data = $db->query($sql);
        if(!$data){
            echo json_encode(array(),JSON_UNESCAPED_UNICODE);
            exit;
        }
        foreach ($data as $key=>$item){
           $data[$key]['AX_lastvandor']=$this->getvandor($item['U_ItemCode'], $db,'CardName');
        }
        $sort = array(
            'direction' => 'SORT_DESC', //排序顺序标志 SORT_DESC 降序；SORT_ASC 升序
            'field'     => 'AX_lastvandor',       //排序字段
        );
        
        $arrSort = array();
        foreach($data AS $uniqid => $row){
            foreach($row AS $key=>$value){
                $arrSort[$key][$uniqid] = $value;
            }
        }
        
        array_multisort($arrSort[$sort['field']], constant($sort['direction']), $data);
        echo json_encode($data,JSON_UNESCAPED_UNICODE);
    }
    
    //根据物料编号  获取推荐供应商
    function getvandor($itemcode,$db,$clm='CardName'){
       
        $sql = "select [dbo].[AX_lastvandor]('{$itemcode}','{$clm}') AX_lastvandor";
        $data = $db->query($sql);
        return $data[0]['AX_lastvandor'];
    }

    function down(){
        $this->initialize();
        $itemCodes = rtrim(I('codes'),',');
        $codearr = explode(',', $itemCodes);
        $str = "'".implode("','", $codearr)."'";
        $type = I('type');
        if(!$itemCodes){
            $this->error('请选择物料');
            exit;
        }
        $date = date('Y-m-d',time());
        $pm = session('Pleader');
        // T.U_PManager='{$pm}' and
        $sql = "SELECT  U_CitemCd ,U_CitemNm,T.U_PManager,t.U_OrderId,t.LineId,t.U_ItemCode,t.U_ItemName,t.U_Qty,U_State,U_City,U_Address,U_Cstname,U_phone,U_SOrderId FROM [@ti_z0081] AS t INNER JOIN [@ti_z0080] AS t2 ON t.DocEntry = t2.DocEntry WHERE   t.U_OStatus IN ('1','2' ,'3') and  t.U_Replace = 'Y' and t2.U_DocDate = '{$date}'and t.U_ItemCode in({$str}) ORDER BY U_orderId desc";
        $db = new Sqlserver();
        $db->connent();
        $data = $db->query($sql);
        Vendor('Excel.PHPExcel');
        $objPHPExcel = new \PHPExcel();
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1','订单号')
            ->setCellValue('B1','导单号')
            ->setCellValue('C1','物料号')
            ->setCellValue('D1','产品经理')
            ->setCellValue('E1','商户物料编号')
            ->setCellValue('F1','商户物料名称')
            ->setCellValue('G1','数量')
            ->setCellValue('H1','省')
            ->setCellValue('I1','市')
            ->setCellValue('J1','地址')
            ->setCellValue('K1','收货人')
            ->setCellValue('L1','电话')
            ->setCellValue('M1','SAP订单号')
            ->setCellValue('N1','快递公司')
            ->setCellValue('O1','快递单号');
        $i=2;                //定义一个i变量，目的是在循环输出数据是控制行数
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getNumberFormat()->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);
        $objPHPExcel->getActiveSheet()->getStyle('L1')->getNumberFormat()->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);
        foreach ($data as $key=>$v){
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('A' . $i, $v['U_OrderId'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('L' . $i, $v['U_phone'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->getStyle('A' . $i)->getNumberFormat() ->setFormatCode("@");
            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue("A".$i, $v['U_OrderId']." ")
                ->setCellValue("B".$i, $v['LineId'])
                ->setCellValue("C".$i, $v['U_ItemCode'])
                ->setCellValue("D".$i,  $v['U_PManager'])
                ->setCellValue("E".$i,  $v['U_CitemCd'])
                ->setCellValue("F".$i, $v['U_CitemNm'])
                ->setCellValue("G".$i,  $v['U_Qty'])
                ->setCellValue("H".$i, $v['U_State'])
                ->setCellValue("I".$i, $v['U_City'])
                ->setCellValue("J".$i,  $v['U_Address'])
                ->setCellValue("K".$i,  $v['U_Cstname'])
                ->setCellValue("L".$i, $v['U_phone'])
                ->setCellValue("M".$i,  $v['U_SOrderId'])
                ->setCellValue("N".$i, '')
                ->setCellValue("O".$i, '');
            $i++;
        }
        $objPHPExcel->getSheet(0)->getColumnDimension('A')->setWidth(35);
        $objPHPExcel->getSheet(0)->getColumnDimension('E')->setWidth(22);
        $objPHPExcel->getSheet(0)->getColumnDimension('F')->setWidth(70);
        $objPHPExcel->getSheet(0)->getColumnDimension('J')->setWidth(70);
        $objPHPExcel->getSheet(0)->getColumnDimension('D')->setWidth(20);
        $objPHPExcel->getSheet(0)->getColumnDimension('L')->setAutoSize(true);

        $objPHPExcel->getActiveSheet()->setTitle('aa');
        $objPHPExcel->setActiveSheetIndex(0);
        $filename='Order'. date('YmdHis',time());
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');

        if($type){
            $PATH = '/Uploads/Download/data/'.date('Ymd').'/';
            if(!file_exists(WWWROOT.$PATH)){
                mkdir(WWWROOT.$PATH);
            }

            $objWriter->save(WWWROOT.$PATH.$filename . '.xls');
            $to = I('tomail');
            $res =  $this->sendEamil($to, $filename, '附件内容', WWWROOT.$PATH.$filename . '.xls');
            echo json_encode($res,JSON_UNESCAPED_UNICODE);
            exit;
        }


        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $filename . '.xls"');
        header('Cache-Control: max-age=0');
        $objWriter->save('php://output');

    }
    
    
    function initialize() {
        require 'Application/Home/ORG/Util/Sqlserver.class.php';
    }
    
    function getEmail(){
        $this->initialize();
        $name = I('name');
        $db = new Sqlserver();
        $db->connent();
        echo  $this->getvandor($name, $db,'CardCodeEmail');
    }
    
    private function sendEamil($toMail, $title, $content, $Attachment)
    {
        $respon = array(
            'code' => 0,
            'msg' => ''
        );
       import("@.ORG.Util.send");
        $mail = new \PHPMailer(true);
    
        $mail->CharSet = "UTF-8"; 
        $mail->IsSMTP(); 
        // 这里指定字符集！解决中文乱码问题
        $mail -> Encoding = "base64";
        $mail->SMTPAuth = true; 
        $mail->SMTPSecure = "ssl"; 
        $mail->Host = "smtp.exmail.qq.com"; 
        $mail->Port = 25; 
        $mail->Username = 'noreply@g-town.com.cn'; 
        $mail->Password ='VFe8TP$5'; 
        $mail->SetFrom($mail->Username, '海牙湾'); 
        //$mail->AddReplyTo($mail->Username , '测试');
        $mail->AddReplyTo(session('emp_no').'@g-town.com.cn',session('emp_no'));
        // 设置邮件回复人地址和名称
        $mail->Subject = '【'.$title.' 】'; // 设置邮件标题
        $mail->AltBody = "为了查看该邮件，请切换到支持 HTML 的邮件客户端";
        
        // 可选项，向下兼容考虑
        $mail->MsgHTML($content); // 设置邮件内容
     
        $mail->AddAddress($toMail, "");
        if ($Attachment){
           $mail->AddAttachment($Attachment); // 附件
        }
    
        if (! $mail->Send()) {
           
            $respon['code'] = - 1;
            $respon['msg'] = $mail->ErrorInfo;
        } else {
            $respon['msg'] = "邮件发送成功！";
        }

        return $respon;
    }
    
    /**
     * 中银订单反馈记录处理
     */
    function ccborder(){
        $m = $this->db_ccb('OrderPush');
        $keyword = I('keyword');
        if($keyword){
        $keyword = rtrim($keyword);
        $keyword = ltrim($keyword);
        $map['order_code'] = array('like','%'.$keyword.'%');
        }
        $this->_list($m, @$map);
        $this->assign('keyword',$keyword);
        $this->display('ccborder');
    }
    
    /**
     * 删除中银推送记录
     */
    function delccbpush(){
        $id = I('id');
        $m = $this->db_ccb('OrderPush');
        $info = $m->where("id={$id}")->find();
        $res = false;
        if($info){
            $res = $m->where("id={$id}")->delete();
            $this->db_ccb('Order')->where("order_code={$info['order_code']}")->save(array('status'=>0));;
        }
        echo $res;
        
    }
    
    function db_ccb($tabname){
        return M($tabname,'tools_','DB_CONFIG_CCB');
    }

    function updatestockofboc365byexcel(){
        //echo 9999;exit;
        $this->display();
    }

    function doimportupdatestockofboc365byexcel()
    {
        $tag =time();
        $today = date("Y-m-d H:i:s");
        $time = $today;
        // excel 表头 与 mysql 表头对应关系
        $orderHeadArray = array(

//            '礼品编号' =>'product_id', //A
//            '礼品名称' =>'product_name', //B
//            '礼品型号' =>'product_spec', //C
//            '当前库存' =>'stock_number', //D
             // '供应商名称'=>
            '品牌及名称'=> 'product_name',
            '规格或型号'=> 'product_spec',
            '上架礼品积分值'=>'product_quality',
            '礼品编号' =>'product_id',
            '上架礼品名称'=>'sale_name',
            '库存'=>'stock_number'

        );

        if (!empty($_FILES)) {
            import("@.ORG.UploadFile");
            $config = array(
                'allowExts' => array('xlsx', 'xls'),
                'savePath' => './exceltojh/',
                'saveRule' => 'time',
            );
            $upload = new UploadFile($config);
            if (!$upload->upload($config['savePath'])) {
                $this->error($upload->getErrorMsg());
            } else {

                $info = $upload->getUploadFileInfo();
                $theType = $info[0]['type'];
                //echo $theType;die();
                if($theType != "application/vnd.ms-excel" && $theType != "application/octet-stream" && $theType != "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
                {
                    //var_dump($theType);die();
                    $this->assign('errorInfo',"文件类型错误！");
                    $this->display('updatestockofboc365byexcel');
                    return;
                }

                $name = $info[0]['savename'];
                Vendor('Excel.PHPExcel');
                $filename= $config['savePath'].$name;

                $objPHPExcel = \PHPExcel_IOFactory::load($filename);

                $sheetData   = $objPHPExcel -> getActiveSheet() -> toArray(null, true, true, true);

                $currentSheet = $objPHPExcel->getSheet(0);
                $allColumn = $currentSheet->getHighestColumn();//取到最大列数
                $allRow = $currentSheet->getHighestRow();//取到最大行数

                // excel 中表头
                $excelHeadCN = $sheetData[1];
                $excelHead = array();
                foreach ($excelHeadCN as $key => $value) {
                    $excelHead[$key] = $orderHeadArray[$value];
                }
                unset($excelHead['']);
                foreach ($excelHead as $key => $value) {
                    if (empty($value)) {
                        unset($excelHead[$key]);
                    }
                }
                // Table表头与Excel列对应关系
                //var_dump($excelHead);
                unset($sheetData[1]); //删除excel表头 列名等行数据

                $mergeStr = '';
                $countNum = 0;
                //echo "<pre>";
                foreach ($sheetData as $key => $v) {
                    //数据 $key行号 $v数组

                    $targetData = array();
                    foreach ($v as $inkey => $value) {
                        //Core
                        $targetData[$excelHead[$inkey]] = trim($value);
                    }
                    unset($targetData['']);

                    $targetData['product_name'] = addslashes($targetData['product_name']);
                    $targetData['product_spec'] = addslashes($targetData['product_spec']);
                   $targetData['sale_name'] = addslashes($targetData['sale_name']);

                    // 补全数据
                    //$targetData['oa_upload_wave_no'] = $tag;
                    $targetData['create_time'] = time();
                    $targetData['handdle_name'] = session('emp_no');

                    $str = "'" . implode("','", $targetData) . "'";

                    $countNum++;

                    if ($countNum == 1) $mergeStr .= "({$str})";
                    else $mergeStr .= ", ({$str})";

                    //print_r($targetData);
                }
                //print_r($targetData); exit;
                //exit;
                try {
                    $sql = " insert into think_boc365_stock  (" . implode(',', array_keys($targetData)) . ") values $mergeStr";
                    //echo $sql."<br>";
                    //echo $sql;die();
                    //var_dump( M('boc365_stock'));
                    $sapbankRelationModel = M('boc365_stock');
                    $result = $sapbankRelationModel->execute($sql);
                    //echo $sapbankRelationModel->getLastSql();
                    //exit;
                }catch(Exception $e)
                {

                    echo $e->getMessage();
                    exit;
                }
                //exit;
                $return = 0;
                $errorStr = '导入不成功！';
                if ($result) {
                    $return = 1;
                    $errorStr = '导入成功！';
                }
                //echo json_encode(array('data' => $return, 'msg' => $errorStr), 1);
                 //exit();
                $this->assign('errorInfo',$errorStr);
                $this->display('updatestockofboc365byexcel');

            }
        }
    }

    function listupdatestockofboc365byexcel(){

        $this->display();
    }

    public function getlistupdatestockofboc365byexcel()
    {
        $model =M('boc365Stock');
        $pageIndex = I('pageIndex');
        $pageSize = I('pageSize')?:50;
        $where='1 = 1 ';
        $product_name= I('product_name');
        $product_id= I('product_id');
        $sap_item_code= I('sap_item_code');
        if($product_name){

            $where.= " and product_name like '%". trim($product_name) . "%'";
        }
        if($product_id){
            $where.= " and product_id = '". trim($product_id) . "'";
        }
        if($sap_item_code){
            $where.= " and sap_item_code = '". trim($sap_item_code) . "'";
        }
        $all =$model->where($where)->order("id desc")->select();
        $total = count($all);
        $res = $model->where($where)->order("id desc")->limit($pageIndex*$pageSize,$pageSize)->select();
        foreach ($res as $k=>$v)
        {
            $res[$k]['create_time']=date("Y-m-d H:i:s");
        }
        echo json_encode(array('total'=>$total,'data'=>$res));exit;

    }

    public function downloadboc365stock()
    {
        $model =M('boc365Stock');
        $where='1 = 1 ';
        $product_name= I('product_name');
        $product_id= I('product_id');
        $sap_item_code= I('sap_item_code');
        if($product_name){

            $where.= " and product_name like '%". trim($product_name) . "%'";
        }
        if($product_id){
            $where.= " and product_id = '". trim($product_id) . "'";
        }
        if($sap_item_code){
            $where.= " and sap_item_code = '". trim($sap_item_code) . "'";
        }
        $data = $model->where($where)->order("id desc")->select();
        Vendor('Excel.PHPExcel');
        $objPHPExcel = new \PHPExcel();
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1','中行商品id')
            ->setCellValue('B1','品牌及名称')
            ->setCellValue('C1','规格或型号')
            ->setCellValue('D1','上架礼品积分值')
            ->setCellValue('E1','sap编号')
            ->setCellValue('F1','上架礼品名称')
            ->setCellValue('G1','库存')
            ->setCellValue('H1','库存类型');
        $i=2;                //定义一个i变量，目的是在循环输出数据是控制行数
        $objPHPExcel->getActiveSheet()->getStyle('D1')->getNumberFormat()->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);
        $objPHPExcel->getActiveSheet()->getStyle('G1')->getNumberFormat()->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);
        foreach ($data as $key=>$v){
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('D' . $i, $v['product_quality'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('G' . $i, $v['stock_number'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->setActiveSheetIndex(0)

                ->setCellValue("A".$i,  $v['product_id'])
                ->setCellValue("B".$i, $v['product_name'])
                ->setCellValue("C".$i, $v['product_spec'])
                ->setCellValue("D".$i, $v['product_quality']." ")

                ->setCellValue("E".$i,  '')
                ->setCellValue("F".$i, $v['sale_name'])
                ->setCellValue("G".$i,  $v['stock_number']);
            $i++;
        }
        $objPHPExcel->getActiveSheet()->setTitle('中行365商品信息列表');
        $objPHPExcel->setActiveSheetIndex(0);
        $filename='boc365product'. date('YmdHis',time());
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $filename . '.xls"');
        header('Cache-Control: max-age=0');
        $objWriter->save('php://output');
    }

    function showupdatestockofboc365byexcel(){

        $oaUploadWaveNo = I('oaUploadWaveNo');
        $this->assign('oaUploadWaveNo',$oaUploadWaveNo);
        $this->display();

    }

    public function showupdatestockofboc365byexceldetail()
    {
        $model =M('boc365Stock');
        $pageIndex = I('pageIndex');
        $pageSize = I('pageSize')?:50;
        $oaUploadWaveNo = I('oaUploadWaveNo');
        $where="1 = 1 AND oa_upload_wave_no = '{$oaUploadWaveNo}'";
        $total =$model->where($where)->order("id desc")->count();
        $res = $model->where($where)->order("id desc")->limit($pageIndex*$pageSize,$pageSize)->select();
        echo json_encode(array('total'=>$total,'data'=>$res));exit;
    }
    public function editboc365()
    {
        $product_id=trim(I('product_id'));
        $model =M('boc365Stock');
        $data= $model->where(" product_id='".$product_id."'")->find();
        $this->assign('data',$data);
        $this->display();
    }

    public function editingboc365()
    {
        $result=array('msg'=>'','state'=>200);
        $model =M('boc365Stock');
        $product_id=trim(I('product_id'));
        $data=array(
            'product_name'=>I('product_name'),
            'product_spec'=>I('product_spec'),
            'product_quality'=>I('product_quality'),
            'sale_name'=>I('sale_name'),
            'stock_number'=>I('stock_number'),
            'stock_type'=>trim(I('type')),
            'enable'=>trim(I('enable')),
            'sap_item_code'=>trim(I('sap_item_code')),
        );

       $condition='product_id="'.$product_id.'"';

      $model->where($condition)->save($data);
        $info='';
        if(trim(I('type'))==1)
        {
            $info='修改'.$product_id."为sap库存";
        }else{
            $info='修改'.$product_id."为手动库存".I('stock_number');
        }
        $logs=array(
            'log_time'=>time(),
            'handdle_name'=> session('emp_no'),
            'log_info'=> $info,
            'product_id'=>$product_id
        );
        //print_r( $logs);exit;
        M('boc365StockLog')->add($logs);

       $result['msg']="更新成功";
       echo json_encode($result);exit;
    }

    function db_ib($tabname){
        return M($tabname,'oms_','DB_CONFIG_IB');
    }

    function uploadShipping(){
//        $rows=$this->db_ib('Order')->where("orderId=1026435098")->find();
//        print_r($rows);exit;
        $this->display();
    }

    function uploadingShipping(){

        //$result=array('msg'=>'','state'=>200);
        set_time_limit(0);
        ini_set("memory_limit", "-1");
        $model =$this->db_ib('Order');
        $str='';
        $batch_no=date("YmdHi");
        $orderHeadArray = array(
            '订单号'=> 'orderId',
            '快递商'=> 'expCom',
            '快递单号'=>'expNo'

        );

        if (!empty($_FILES)) {
            import("@.ORG.UploadFile");
            $config = array(
                'allowExts' => array('xlsx', 'xls'),
                'savePath' => './exceltojh/',
                'saveRule' => 'time',
            );
            $upload = new UploadFile($config);
            if (!$upload->upload($config['savePath'])) {
                $this->error($upload->getErrorMsg());
            } else {

                $info = $upload->getUploadFileInfo();
                $theType = $info[0]['type'];
                //echo $theType;die();
                if($theType != "application/vnd.ms-excel" && $theType != "application/octet-stream" && $theType != "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
                {
                    //var_dump($theType);die();
                    $this->assign('errorInfo',"文件类型错误！");
                    $this->display('updatestockofboc365byexcel');
                    return;
                }

                $name = $info[0]['savename'];
                Vendor('Excel.PHPExcel');
                $filename= $config['savePath'].$name;

                $objPHPExcel = \PHPExcel_IOFactory::load($filename);

                $sheetData   = $objPHPExcel -> getActiveSheet() -> toArray(null, true, true, true);

                $currentSheet = $objPHPExcel->getSheet(0);
                $allColumn = $currentSheet->getHighestColumn();//取到最大列数
                $allRow = $currentSheet->getHighestRow();//取到最大行数

                // excel 中表头
                $excelHeadCN = $sheetData[1];
                $excelHead = array();
                foreach ($excelHeadCN as $key => $value) {
                    $excelHead[$key] = $orderHeadArray[$value];
                }
                unset($excelHead['']);
                foreach ($excelHead as $key => $value) {
                    if (empty($value)) {
                        unset($excelHead[$key]);
                    }
                }
                // Table表头与Excel列对应关系
                //var_dump($excelHead);
                unset($sheetData[1]); //删除excel表头 列名等行数据

                $mergeStr = '';
                $countNum = 0;
                //echo "<pre>";
                foreach ($sheetData as $key => $v) {
                    //数据 $key行号 $v数组

                    $targetData = array();
                    foreach ($v as $inkey => $value) {
                        //Core
                        $targetData[$excelHead[$inkey]] = trim($value);
                    }
                    unset($targetData['']);

                    $targetData['orderId'] = addslashes($targetData['orderId']);

                    $targetData['expCom'] = addslashes($targetData['expCom']);
                    $targetData['expNo'] = addslashes($targetData['expNo']);
                    $status=0;
                    $targetData['orderId']= preg_replace('/^\s+\r?\n/m', '', $targetData['orderId']);
                    if(trim($targetData['orderId']!=''))
                    {

                        if(trim($targetData['expCom'])=='')
                        {
                            $status=1;
                            $str.="订单:".$targetData['orderId']."物流公司不存在"."\n";
                        }
                        if(trim($targetData['expNo'])=='')
                        {
                            $status=2;
                            $str.="订单:".$targetData['orderId']."快递单号不存在"."\n";
                        }

                   // INSERT INTO `ib`.`oms_shipping_log` (`orderId`, `expNo`, `expCom`) VALUES ('10086', 'zto', '10010');

                        $sql = " INSERT INTO `oms_shipping_log` (`orderId`, `expNo`, `expCom`,`batch_no`,`status`,`ctime`) VALUES ('".$targetData['orderId']."', '". $targetData['expNo']."', '". $targetData['expCom']."', '".$batch_no."',".$status.", '".time()."') ";
                        $this->db_ib('ShippingLog')->execute($sql);




                        $data=array(
                            'expCom'=> $targetData['expCom'],
                            'expNo'=>$targetData['expNo'],
                            'orderStatus'=>230

                        );
                        $condition='orderId="'. $targetData['orderId'].'" and orderStatus<=230 ';
                        $model->where($condition)->save($data);
                    }
                    //echo  $model->getLastSql(); exit;

                }

            }
        }
        if($str!='')
        {
            //$receiver = "austin@g-town.com.cn";
            $ccArray = array('eddy.chen@g-town.com.cn');

            $this->sendEmail('eddy.chen@g-town.com.cn', "批次：". $batch_no . "上传快递信息有异常", $str, '', $ccArray);

        }
        $this->success('导入成功！',U('Order/boc_Ship_list'));
       // $result['msg']="更新成功";
       // echo json_encode($result);exit;


    }

    function boc_Ship_list(){
        $this->display();
    }

    function boc_get_Ship_list(){
        //$model =M('boc365Stock');
        //cime: cime,orderId:orderId,batch_no:batch_no
        $model =$this->db_ib('ShippingLog');
        $pageIndex = I('pageIndex');
        $pageSize = I('pageSize')?:500;
        $where='1 = 1 ';
        $ctime= I('ctime');
        $batch_no= trim(I('batch_no'));
        $orderId= trim(I('orderId'));
        if($orderId){
            $where.= " and orderId  = '". trim($orderId) . "'";
        }
        if($batch_no){
            $where.= " and batch_no = '". trim($batch_no) . "'";
        }
//        if($cime){
//            $where.= " and cime BETWEEN  '". trim($cime) . "' and '". trim($cime)." 23:59:59"."'";
//        }
        if($ctime)
        {
            $where .=" and FROM_UNIXTIME(ctime,'%Y-%m-%d') = '{$ctime}'";
        }

        $all =$model->where($where)->order("status desc,id desc")->select();
        $total = count($all);
        $res = $model->where($where)->order("status desc,id desc")->limit($pageIndex*$pageSize,$pageSize)->select();
        foreach($res as $key=>$value)
        {
            $res[$key]['ctime']=date("Y-m-d H:i:s",$value['ctime']);
        }
        //echo $model->getLastSql();exit;
//        foreach ($res as $k=>$v)
//        {
//            $res[$k]['create_time']=date("Y-m-d H:i:s");
//        }
        echo json_encode(array('total'=>$total,'data'=>$res));exit;
    }

}